import os
from string import Template

root  = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
project = os.path.basename(root)
print("project name: "+project)
serviceRoot = project+"/core/service"
daoRoot = project+"/core/dao"
tablePackage = project+"/core/dao/table"
commonPackage = project+"/core/service/common"
localwrapPackage  = project+"/core/localwrap"

packages = {
	"graphroute":{
		"Graphs":{
			"daoPackage":"${daoPackage}",
			"servicePackage":"graphs",
			"dao":"Graphs",
			"service":"Graphs",
			"table":"Graph"
		},
		"GraphElements":{
			"daoPackage":"${daoPackage}",
			"dao":"GraphElements",
			"table":"GraphElement"
		},
		"${dao}":{
			"daoPackage":"${daoPackage}",
			"dao":"${dao}",
			"table":"GraphUser"
		},
		"GraphElementDatas":{
			"daoPackage":"${daoPackage}",
			"dao":"GraphElementDatas",
			"table":"GraphElementData"
		}
	},
}

routeTpl ='''package ${package}

import (
	"${daoRoot}/${daoPackage}"
	"${serviceRoot}/${servicePackage}"
	"${project}/http/routes"

	"github.com/RocksonZeta/irisx"
	"github.com/kataras/iris/v12"
)

func Route${route}(party iris.Party) {
	party.Get("/", func(ctx iris.Context) {
		c := ctx.(*irisx.Context)
		id := c.CheckQuery("id").Int(0)
		routes.Check(c)
		r := ${servicePackage}.${service}{}.Get(id)
		c.Ok(r)
	})
	party.Post("/", func(ctx iris.Context) {
		c := ctx.(*irisx.Context)
		var param ${daoPackage}.${dao}AddParam
		param.Name = c.CheckBody("name").String()
		routes.Check(c)
		r := ${servicePackage}.${service}{}.Add(param)
		c.Ok(r)
	})
	party.Post("/update", func(ctx iris.Context) {
		c := ctx.(*irisx.Context)
		var param ${daoPackage}.${dao}UpdateParam
		param.Id = c.CheckBody("id").NotEmpty().Int(0)
		param.Name = c.CheckBody("name").Len(0, 100).String()
		routes.Check(c)
		${servicePackage}.${service}{}.Update(param)
		c.Ok(nil)
	})
	party.Post("/del", func(ctx iris.Context) {
		c := ctx.(*irisx.Context)
		id := c.CheckBody("id").NotEmpty().Int(0)
		routes.Check(c)
		${servicePackage}.${service}{}.Delete(id)
		c.Ok(nil)
	})
}

'''
routeTestTpl ='''


'''



def write(content , package, file) :
	d = os.path.join(os.path.dirname(root),serviceRoot,package)
	if not os.path.exists(d) :
		os.makedirs(d)
	dst = os.path.join(d,file)
	if os.path.exists(dst) :
		print(dst +" has already exists,ignore it")
		return
	print("create "+dst)
	f = open(dst,"w+")
	f.write(content)
	f.close()

def make():
	tpl = Template(routeTpl)
	testTpl = Template(routeTestTpl)
	for package,routes in packages.items():
		for name,route in routes.items():
			param = {"package":package,"route":name,"service":route['service'],"dao":route['dao'],"table":route['table'],'daoPackage':route['daoPackage'],"serviceRoot":serviceRoot,"daoRoot":daoRoot,"tablePackage":tablePackage,"commonPackage":commonPackage,"localwrapPackage":localwrapPackage}
			service=tpl.substitute(param)
			write(service, package , name+".go")
			serviceTest=testTpl.substitute(param)
			write(serviceTest, package , name+"_test.go")
			

make()